#!/usr/bin/env python
# encoding: utf-8
"""
    @author:水痕
    @time:2018-09-18 08:42:42:31
    @email:332904234@qq.com
    @version:1.0
    @fileName:my_blogs.py
    @describe: 个人博客中心
"""

from django.shortcuts import render, redirect
from django.views.generic import View
from django.http import JsonResponse
from django.contrib.auth.decorators import login_required
from django.utils.decorators import method_decorator
from pure_pagination import Paginator, EmptyPage, PageNotAnInteger
from article import models

from django.contrib.auth import get_user_model

# 从系统中获取自己定义的user表
User = get_user_model()


@method_decorator(login_required, name='dispatch')
class MyBlogsView(View):
    """
    个人博客request.user.is_authenticated
    """

    def get(self, request, *args, **kwargs):
        username = request.user or None
        if username:
            user_obj = User.objects.filter(username=username).first()
            # 获取文章列表
            article_querySet = models.ArticleModel.objects.filter(author_id=user_obj.id).order_by('-create_at')
            # 设置分页返回数据
            try:
                page = request.GET.get('page', 1)
            except PageNotAnInteger:
                page = 1

            p = Paginator(article_querySet, 10, request=request)

            article_list = p.page(page)
            return render(request, 'my-blogs.html', locals())
        return redirect('index')
